package com.guandi.geekbrowser.primary.service.impl;

import com.guandi.geekbrowser.primary.entity.User;
import com.guandi.geekbrowser.primary.repository.UserRepository;
import com.guandi.geekbrowser.primary.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;

import javax.persistence.criteria.*;
import java.util.List;
import java.util.Optional;

@Service
public class UserServiceImpl implements UserService {

    @Autowired
    private UserRepository userRepository;
    @Override
    public void saveUser(User user) {
        userRepository.save(user);
    }

    @Override
    public User findByNameAndPassword(String name, String password) {
        return userRepository.findByNameAndPassword(name, password);
    }

    @Override
    public Optional<User> findById(String id) {
        return userRepository.findById(id);
    }

    @Override
    public User findByName(String name) {
        return userRepository.findByName(name);
    }

    @Override
    public List<User> findAll() {
        return userRepository.findAll();
    }

    @Override
    public Page<User> findAllByAdmin(String name,int pageSize,int pageNumber) {
        Pageable pageable = PageRequest.of(pageNumber-1, pageSize);
        Specification<User> spe = new Specification<User>() {
            @Override
            public Predicate toPredicate(Root<User> root, CriteriaQuery<?> criteriaQuery, CriteriaBuilder criteriaBuilder) {
                Path<String> userName = root.get("name");
                Predicate namePre = criteriaBuilder.like(userName, "%"+name+"%");
                return namePre;
            }
        };
        return userRepository.findAll(spe,pageable);
    }
}
